package net.openmob.mobileimsdk.android.demo.event;

import android.util.Log;

import net.openmob.mobileimsdk.android.demo.MainActivity;
import net.openmob.mobileimsdk.android.demo.SpeechUtils;
import net.openmob.mobileimsdk.android.event.ChatBaseEvent;

import java.util.Observer;

/**
 * 与IM服务器的连接事件在此ChatBaseEvent子类中实现即可。
 *
 * @author x55admin, 20170501
 * @version.1.1
 */
public class ChatBaseEventImpl implements ChatBaseEvent {
    private final static String TAG = ChatBaseEventImpl.class.getSimpleName();

    private MainActivity mainActivity = null;

    // 本Observer目前仅用于登陆时（因为登陆与收到服务端的登陆验证结果
    // 是异步的，所以有此观察者来完成收到验证后的处理）
    private Observer loginOkForLaunchObserver = null;

    @Override
    public void onLoginMessage(int dwErrorCode) {
        if (dwErrorCode == 0) {
            Log.i(TAG, "【DEBUG_UI】IM服务器登录/重连成功！");
            // TODO 以下代码仅用于DEMO哦
            if (this.mainActivity != null) {
                this.mainActivity.refreshMyid();
                this.mainActivity.showIMInfo_green("IM服务器登录/重连成功,dwErrorCode=" + dwErrorCode);
            }
        } else {
            Log.e(TAG, "【DEBUG_UI】IM服务器登录/连接失败，错误代码：" + dwErrorCode);

            // TODO 以下代码仅用于DEMO哦
            if (this.mainActivity != null) {
                this.mainActivity.refreshMyid();
                this.mainActivity.showIMInfo_red("IM服务器登录/连接失败,code=" + dwErrorCode);
            }
        }

        // 此观察者只有开启程序首次使用登陆界面时有用
        if (loginOkForLaunchObserver != null) {
            loginOkForLaunchObserver.update(null, dwErrorCode);
            loginOkForLaunchObserver = null;
        }
    }

    @Override
    public void onLinkCloseMessage(int dwErrorCode) {
        Log.e(TAG, "【DEBUG_UI】与IM服务器的网络连接出错关闭了，error：" + dwErrorCode);

        // TODO 以下代码仅用于DEMO哦
        if (this.mainActivity != null) {
            this.mainActivity.refreshMyid();
            this.mainActivity.showIMInfo_red("与IM服务器的连接已断开, 自动登陆/重连将启动! (" + dwErrorCode + ")");
        }
    }

    public void setLoginOkForLaunchObserver(Observer loginOkForLaunchObserver) {
        this.loginOkForLaunchObserver = loginOkForLaunchObserver;
    }

    public ChatBaseEventImpl setMainActivity(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
        return this;
    }
}
